<template>
	<div class=""  v-loading="loading">
		  <div class="knowledge-set-test">
			  	<div class="knowledge-set-test-type" v-show="0">
			  		<template>
			  		  <el-radio v-model="question.testType" label="1" v-if="question.testType == 1">手动录入</el-radio>
			  		  <el-radio v-model="question.testType" label="2" v-if="question.testType == 2">图片录入</el-radio>
			  		</template>
			  	</div>

			  	<div class="knowledge-set-test-condition knowledge-type-c">
			  		 <template>
			  		 	<el-radio-group v-model="question.type" >
			  		 		<template v-for="item of questionTypeList">
			  		 			<el-radio :label="item.id" v-if="question.type == item.id">{{item.name}}</el-radio>
			  		 		</template>
			  		 	</el-radio-group>
			  		 </template>
			  	</div>
				
				<!--手动录入  -->
			  	<template >
			  		<div class="knowledge-set-tes-txt"  v-show="question.testType == 1">
			  			<div class="knowledge-operation">
			  					<span>题干<i>*</i></span>
			  					<div class="knowledge-">
			  						<vue-ueditor-wrap  id="ueditor1"  class="Ueditor-txt"  v-model="question.stem" ref="ueditorStem" :config="config1"></vue-ueditor-wrap>
			  					</div>
			  			</div>
			  		</div>
			  		<!--  -->
			  		<ul  v-if="question.testType == 1 && (question.baseid == 1 || question.baseid == 2 )">
				  		<li class="knowledge-operation knowledge-outline" v-for="(option, key2) of question.options" :key="key2">
				  			<span>{{option.name}}<i>*</i></span>
				  			<div class="knowledge-">
								
								<vue-ueditor-wrap  class="Ueditor-txt" v-model="option.value" :ref="`ueditor${key2}`" :config="config1" :id="'ueditor-'+key2"></vue-ueditor-wrap>
				  			</div>
				  		</li>
				  	</ul>

				  	<div class="answer-outline" v-if="question.testType == 1 && (question.baseid == 1 || question.baseid == 2 )">
				  		<span  v-preventReClick @click="removeAnswer(4)" v-show="question.baseid == 1 && question.answer.length < 4">
				  			<i class="el-icon-plus"></i>
				  			添加选项
				  		</span>
				  		<span  v-preventReClick @click="removeAnswer(4)" v-show="question.baseid == 2 && question.answer.length < 7">
				  			<i class="el-icon-plus"></i>
				  			添加选项
				  		</span>
				  		<span  v-preventReClick @click="removeAnswer(3)" v-show="question.answer.length > 2">
				  			<i class="el-icon-minus"></i>
				  			移除选项
				  		</span>
				  	</div>
			  	</template>

			  	<!-- 图片录入 -->
			  	<template >

			  		<div class="knowledge-set-tes-img" v-show="question.testType == 2">
			  			
			  			<div class="knowledge-up-img">
			  				<i class="el-icon-circle-close" @click="removeFile($event, 1)" v-show="uploadOptions.imageUrl"></i>
			  				<el-upload class="upload-demo" drag  :multiple="false"
			  				  :show-file-list="false" ref="upload"
			  				  :before-upload="beforeImageUrl"
			  				  :on-success="imageUrlSuccess"
			  				  :action="uploadOptions.target"
			  				  :headers="uploadOptions.headers"
			  				  accept=".jpg,.jpeg,.png,bmp"
			  				  :auto-upload="true">
			  
			  				 <img v-show="uploadOptions.imageUrl" :src="uploadOptions.imageUrl" class="avatar">
			  				 
			  				  <template >
			  				  	<div class="upload-box">
			  				  		<img src="../../../assets/images/upimg.png" class="icon-upload-img">
			  				  		<div class="el-upload__text">点击上传题目 或 将图片拖到此处</div>
			  				  		<div class="el-upload__tip">支持bmp/jpg/png/jpeg格式，且不超过2mb</div>
			  				  	</div>
			  				  </template>
			  				</el-upload>
			  			</div>

		

		  				<div class="knowledge-up-img">
			  				<i class="el-icon-circle-close" @click="removeFile($event, 2)" v-show="uploadOptions.resolveUrl"></i>
			  				<el-upload class="upload-demo" drag  :multiple="false"
			  				  :show-file-list="false" ref="uploadResolve"
			  				  :before-upload="beforeResolveUrl"
			  				  :on-success="resolveUrSuccess"
			  				  :action="uploadOptions.target"
			  				  :headers="uploadOptions.headers"
			  				  accept=".jpg,.jpeg,.png,bmp"
			  				  :auto-upload="true">
			  
			  				 <img v-show="uploadOptions.resolveUrl" :src="uploadOptions.resolveUrl" class="avatar">
			  				 
			  				  <template >
			  				  	<div class="upload-box">
			  				  		<img src="../../../assets/images/upimg.png" class="icon-upload-img">
			  				  		<div class="el-upload__text">点击上传解析 或 将图片拖到此处</div>
			  				  		<div class="el-upload__tip">支持bmp/jpg/png/jpeg格式，且不超过2mb</div>
			  				  	</div>
			  				  </template>
			  				</el-upload>
			  			</div>
			  		</div>	

			  	</template>

			  	<div class="knowledge-operation"  v-if="question.baseid == 1 || question.baseid == 2"> 
			  		<span>答案:<i>*</i></span>
			  		<div class="knowledge- knowledge-choice">
			  			<template >
			  				<el-radio-group v-model="question.check[0]" v-show="question.baseid == 1">
			  					<el-radio v-for="(answer, a) of question.answer" :label="answer" :key="a">{{answer}}</el-radio>
			  				</el-radio-group>
			  			</template>

			  			<template >
			  				<el-checkbox-group v-model="question.check" v-show="question.baseid == 2">
			  				    <el-checkbox  v-for="(answer, b) of question.answer" :label="answer" :key="b">{{answer}}</el-checkbox>
			  				</el-checkbox-group>
			  			</template>
			  			<div class="answer-choice" v-if="question.testType == 2">
			  					<i class="el-icon-remove-outline" v-preventReClick @click="removeAnswer(1)" v-show="question.answer.length > 2"></i>
			  					<i class="el-icon-circle-plus-outline" v-preventReClick @click="removeAnswer(2)"></i>
			  				</div>
			  		</div>
			  	</div>

		  		<!-- 判断题 答案 -->
		  	    <div class="knowledge-operation" v-if="question.baseid == 4">
		  	  		<span>答案:<i>*</i></span>
		  	  		<div class="knowledge- knowledge-choice">
		  	  			

		  	  			<el-radio-group v-model="question.check[0]" >
		  	  				<el-radio label="对" >对</el-radio>
		  	  				<el-radio label="错" >错</el-radio>
		  	  			</el-radio-group>
		  	  		</div>
		  	  	</div>

			  	<div class="knowledge-set-tes-txt"  v-show="question.testType == 1">
			  		<div class="knowledge-operation">
			  			<span>解析<i>*</i></span>
			  			<div class="knowledge-">

			  				<vue-ueditor-wrap  class="Ueditor-txt" v-model="question.resolve" ref="ueditorResolve" :config="config1"  id="resolv"></vue-ueditor-wrap>

			  				<Ueditor v-if="0" v-model="question.resolve" :writeMsg="question.resolve"   id="resolv" :config="config1"  ref="resolv" ></Ueditor>

			  				<vue-editor id="resolve" v-if='0'
				  				:editorToolbar="customToolbar"
				  				placeholder="请输入内容"
				  				@selection-change=""
				  				v-model="question.resolve"></vue-editor>
			  			</div>
			  		</div>
			  	</div>

			  <div class="knowledge-operation" v-if="question.baseid == 3">
			  		<span>空位:<i>*</i></span>
			  		<div class="knowledge-vacancy">
			  			<template>
			  			   <el-select v-model="question.blankNum" placeholder="请选择空位数">
			  			    <el-option
			  			      v-for="(item, index) in 10"
			  			      :key="index" :label="item"  :value="item">
			  			    </el-option>
			  			  </el-select>
			  			</template>
			  		</div>
			  </div>

			  <div class="knowledge-operation">
			  		<span>难度:<i>*</i></span>
			  		<div >
			  			<template>
						  <el-radio-group v-model="question.difficulty" >
						    <!-- <el-radio :label="0">全部</el-radio> -->
						    <el-radio :label="11">容易</el-radio>
						    <el-radio :label="12">普通</el-radio>
						    <el-radio :label="13">困难</el-radio>
						  </el-radio-group>
						</template>
			  		</div>
			  </div>

			  <div class="knowledge-operation">
			  		<span>重点程度:<i>*</i></span>
			  		<div >
			  			<template>
			  			  <el-radio-group v-model="question.keynote">
			  			    <el-radio :label="1">低</el-radio>
			  			    <el-radio :label="2">中</el-radio>
			  			    <el-radio :label="3">高</el-radio>
			  			  </el-radio-group>
			  			</template>  
			  		</div>
			  </div>

			  <div class="knowledge-operation">
			  		<span>题目范围:<i>*</i></span>
                    <testArea ref="testArea" required></testArea>
			  </div>

			  <div class="knowledge-operation">
			  		<span>章节:</span>
			  		<div >
			  			<el-cascader :options="chapterList"  placeholder= '选择章节'
			  			filterable clearable
			  			 v-model="question.chapter"
			  			@change="chapterChange">
			  			</el-cascader>

			  			<el-cascader placeholder= '选择章节' v-if="0"
			  			  :options="chapterList" ref="chapter"
			  			  :props="{ checkStrictly: true }"
			  			   v-model="question.chapter"
			  			  clearable filterable @change="chapterChange">
			  			  </el-cascader>
			  		</div>
			  </div>

			  <div class="knowledge-operation">
			  		<span>知识点:</span>
			  		<div >
			  			<el-cascader :options="knowledgeList"  placeholder= '选择知识点'
			  			:show-all-levels="true" filterable clearable
			  			 v-model="question.knowled"
			  			@change="knowledgeChange">
			  			</el-cascader>

			  			<el-cascader placeholder= '选择知识点' v-if="0"
			  			  :options="knowledgeList" ref="knowle"
			  			  :props="{ checkStrictly: true }"
			  			  v-model="question.knowle"
			  			  :show-all-levels="true"
			  			  clearable filterable @change="knowledgeChange">
			  			  </el-cascader>
			  		</div>
			  </div>


			  <div class="knowledge-operation" v-if="0">
			  		<span>知识点:</span>
			  		<div class="knowledge-vacancy">
			  			<template>
			  			  <el-select v-model="value" placeholder="请选择知识点">
			  			    <el-option
			  			      v-for="(item, index) in vacancyList"
			  			      :key="index" :label="item.name"  :value="item.id">
			  			    </el-option>
			  			  </el-select>
			  			</template>
			  		</div>
			  </div>



		  </div>
		  <span slot="footer" class="dialog-footer knowledge-btn">
		    <el-button @click="Visible"  type="primary" plain >取消</el-button>
		    <el-button type="primary" @click="setQuestion" >保存</el-button>
		  </span>
	</div>
</template>


<script>

	import bus  from  './../base/eventBus.js'
    import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Module
    import testArea  from  './test-area';
    
	export default {
		components: {
            VueUeditorWrap,
            testArea,
        },
		props: ['testObj'],
		data(){
			return{
				showVisible: false,
				testChange: this.testObj,
				settingsVisible: false,
				question: {
					id: '',
					testType: '1',/*1手动，2 图片*/
					type: 0, 		/*试题类型*/
					difficulty: 11,  /*难度*/
					keynote: 1,		/*重点程度*/
					blankNum: '',	/*空位*/
					resolve: '',	/*解析*/
					stem: '',	/*题干*/
					options: [{name: 'A',value: ''},{name: 'B',value: ''}],
					chapter: [],	/*章节*/
					knowled: [],	/*知识点*/
					imageUrl: '',
					resolveUrl:'',
					check: ['A'],
					answer: ['A','B'],
					baseid: 1
				},
				loading: true,
				timingDevice: '',
				time: 1500,
				value: '',
				activeName: '1',
				filterText: '',
				filterText2: '',
				chapterID: [],		/*章节 & 知识点 选中的id*/
				knowledgeID: [],
				vacancyList: [],

				testList: [], 		/*试卷列表*/
				chapterList: [], 	/* 章节列表*/
				knowledgeList: [],	/*知识点*/
				questionTypeList: [],/*题型*/
				chapterList: [], 	/* 章节列表*/
				knowledgeList: [],	/*知识点*/


				customToolbar: [
					[{ list: "ordered" }, { list: "bullet" }],
					[{ 'color': [] }, { 'background': [] }], 
					['clean']
				],
				/*上传*/
				uploadOptions: {
					imageUrl: '',
					resolveUrl: '',
					target: this.BASE_URL + "/api/resource/res_upload",
					headers: { Authorization: `Bearer ` + this.$g.access_token}
				},

				ChoiceArr: ['A','B','C','D','E','F','G'],//数组
				questionID: '',/*试题id*/

		        config1: {
		        	// zIndex: 3,
		        	textIndent: 0,
		        	maximumWords: 2000,
		        	elementPathEnabled: false,/*元素路径*/
					autoHeightEnabled: false,
					autoFloatEnabled: false,//不允许滚动时固定在顶部
					initialContent:'请输入内容...',   //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
					autoClearinitialContent:true, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
					initialFrameWidth: null,
					initialFrameHeight: 150,
					serverUrl: this.BASE_URL+"/static/_/UEditor/1.4.3//php/controller.php?action=uploadimage",
					BaseUrl: this.BASE_URL,
					// UEDITOR_HOME_URL: process.env.BASE_URL+'ueditor/',
					UEDITOR_HOME_URL: process.env.BASE_URL ? process.env.BASE_URL + 'ueditor/' : '/static/ueditor/',
					toolbars: [
						['bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'pasteplain',  'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc','fullscreen',  'simpleupload','link', 'justifyleft', 'justifyright', 'justifycenter', 'lineheight', 'fontfamily', 'fontsize', 'undo', 'redo']
					]
		        },
				  
			}
		},
		created(){
			
		},
		mounted(){
			this.$nextTick(()=>{
                this.ObtainTest()
                this.getQuestionType()	
                this.$refs.testArea.edit = {
                   grade: this.testObj.grade_id,
                   subject: this.testObj.subject_id,
                   edition: this.testObj.version_id,
                   material: this.testObj.masterial_id
                };
                this.$refs.testArea.getGrade();
			})
        },

		methods: {
			
			removeFile(e, type){

				if (type == 1) {
					this.$refs.upload.uploadFiles = [];
					this.uploadOptions.imageUrl = '';
				}else{
					this.$refs.uploadResolve.uploadFiles = [];
					this.uploadOptions.resolveUrl = '';
				}
			},
			/**
			 * 文件列表移除文件时的钩子
			 * @DateTime 2019-08-16T14:26:54+0800
			 * @return   {[type]}                 [description]
			 */
			handleRemove(file, fileList){

			},
			/**上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
			 * [handleBeforeUpload description]
			 * @DateTime 2019-08-16T14:27:14+0800
			 * @param    {[type]}                 file [description]
			 * @return   {[type]}                      [description]
			 */
			beforeImageUrl(file){
				let imgType = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp']

				if (!imgType.includes(file.type)) {
					this.$message.warning('请上传符合格式图片')
					return false
				}else if (file.size > 10480000 ) {
					this.$message.warning('只允许上传10M以内的图片');
					return false
				}else{
					this.uploadOptions.imageUrl = URL.createObjectURL(file);
				}
			},
			beforeResolveUrl(file){

				let imgType = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp']

				if (!imgType.includes(file.type)) {
					this.$message.warning('请上传符合格式图片')
					return false
				}else if (file.size > 10480000 ) {
					this.$message.warning('只允许上传10M以内的图片');
					return false
				}else{
					this.uploadOptions.resolveUrl =  URL.createObjectURL(file);
				}
			},
			/**
			 * 文件上传时的钩子==解析
			 * @DateTime 2019-08-16T14:28:17+0800
			 * @param    {[type]}                 response [description]
			 * @param    {[type]}                 file     [description]
			 * @param    {[type]}                 fileList [description]
			 * @return   {[type]}                          [description]
			 */
			resolveUrSuccess(res, file){
				// console.log(res, file);
				if (res.data.ecode == 200) {
					this.question.resolveUrl = res.data.file_path;
					// console.log(this.question.resolveUrl);
				}
			
			},
			/**
			 * 文件上传成功时的钩子==题干
			 * @DateTime 2019-08-16T14:27:58+0800
			 * @param    {[type]}                 res  [description]
			 * @param    {[type]}                 file [description]
			 * @return   {[type]}                      [description]
			 */
			imageUrlSuccess(res, file) {
				// console.log(res, file);
				if (res.data.ecode == 200) {
					this.question.imageUrl = res.data.file_path;
					// console.log(this.question.imageUrl);
				}
			},
			Visible(){
				// bus.$emit('showVisible', this.showVisible);
				bus.$emit('setTest', false);
			},
			/**
			 *  修改试题
			 * @DateTime 2019-08-14T14:11:34+0800
			 */
			setQuestion(){
     

				/*图片录入*/
				if (this.question.testType == 2) {

					if (this.uploadOptions.imageUrl == '') {
						return this.$message.error('请上传题干图片...')
					}else if (this.uploadOptions.resolveUrl == '') {
						return this.$message.error('请上传解析图片...')
					}
				}else{
                    if (this.question.stem == '') {
						 return this.$message.error(`请填写题干内容`)
                    }else if(this.$refs.ueditorStem.editor.body.innerText.length > 2000){
                        return this.$message.error(`题干内容,已达到字数上限`)
                    }
                    
                    if (this.question.options.length != 0 && (this.question.baseid == 1 || this.question.baseid == 2)) {
						for (let k = 0; k < this.question.options.length; k++) {
                            let option = this.question.options[k];
                            let ueditor = 'ueditor' + k;
							if (option.value == '') {
								return this.$message.error(`请填写${option.name}选择题内容`)
                            }else if(this.$refs[ueditor][0].editor.body.innerText.length > 2000){
								return this.$message.error(`${option.name}选择题内容,已达到字数上限`)
                            }
						}
                    }

                    if (this.question.resolve == ''){
						return this.$message.error(`请填写解析内容`)
                    }else if(this.$refs.ueditorResolve.editor.body.innerText.length > 2000){
                        return this.$message.error(`解释的内容,已达到字数上限`)
                    }

                    if (this.question.baseid == 4) {
						this.question.options = [{name: '对', value: '对'}, {name: '错', value: '错'}]
					}
				};

				if (this.question.baseid == 2 && this.question.check.length == 0) {
					return this.$message.error(`请勾选答案`)
				}

				if ( this.question.baseid == 3 && this.question.blankNum == '') {
					return this.$message.error(`请选择空位`)
				}

		
                /*检验题目范围:不能为空*/
                this.$refs.testArea.valid();
                let noSelect = Object.values(this.$refs.testArea.ruleForm).includes('');
                if(noSelect)return;

				if ( +this.question.testType == 1 && ![1, 2, 4].includes(+this.question.baseid)) {
					this.question.options = [];
					
				}
				/*非选择题时重置答案*/
				if (![1, 2, 4].includes(+this.question.baseid)) {
					// this.question.answer = null
					this.question.check = null
				}

				let success = (res=>{
					this.$message.success(res.msg)
					// this.settingsVisible = false;
                    this.$refs.testArea.reset();//重置题目范围
					bus.$emit('setTest', this.settingsVisible);
					this.$store.commit('SET_QUESTIONCHANGE', new Date())
				});

				/*图片录入*/
				if (this.question.testType == 2) {

					if (this.uploadOptions.imageUrl == '') {
						return this.$message.error('请上传题干...')
					}else if (this.uploadOptions.resolveUrl == '') {
						return this.$message.error('请上传解析...')
					}

					
					if (this.question.imageUrl == '') {
						/*题干图片没有重新上传时，不改变原有题干图片*/
						this.question.imageUrl = this.testObj.content_image_path
					}else if (this.question.resolveUrl == '') {
						/*解析图片没有重新上传时，不改变原有解析图片*/
						this.question.resolveUrl = this.testObj.resolve_image_path
					}

					if (this.question.baseid == 1 || this.question.baseid == 2) {
						if(this.question.answer.length > 0){
							this.question.options = []
							this.question.answer.forEach(item=>{
								this.question.options.push({
									name: item,
									value: ''
								})
							})
						}
					}
				}

				// if ((this.question.testType == 2 && this.question.baseid == 1) || (this.question.testType == 2 && this.question.baseid == 2)) {
				// 	this.question.options = [{name: 'A', value: ''},{name: 'B', value: ''},{name: 'C', value: ''},{name: 'D', value: ''}]
				// }

				if (this.question.baseid == 4) {
					this.question.options = [{name: '对', value: '对'}, {name: '错', value: '错'}]
				}
				/*单选题 ，判断题提交的答案改为数组*/
				if (this.question.baseid == 4 || this.question.baseid == 1) {

					this.question.check = [...this.question.check]
				}

				

		

				/*1手动录入 2图片录入*/
				// let [listid, knowid] = ['', ''];
				// if (this.question.chapter.length != 0) {
				// 	listid = this.question.chapter.pop()
				// }
				// if (this.question.knowled.length != 0) {
				// 	knowid = this.question.knowled.pop()
				// }



				/*非填空题清空空位*/
				if (this.question.baseid != 3) {
					this.question.blankNum = ''
				}

				/*1手动录入 2图片录入*/
				let params = ''
				if (this.question.testType == 1) {
					 params = {
						id: this.question.id,
						pattern: this.question.testType,/*1手动录入 2图片录入*/
						type_id: this.question.type,/*题型id*/
						content: this.question.stem,/*题干*/
						resolve: this.question.resolve,/*解析*/
						option: this.question.options,/*选项 以数组形式 如 option[0]['name'] option[0]['value']*/
						answer: this.question.check,/*答案 以数组形式 如 anseer[0] answer[1]*/
						difficulty_id: this.question.difficulty,/*难度id*/
                        keynote: this.question.keynote,/*重点程度 1低 2中 3高*/
                        
						grade_id: this.$refs.testArea.ruleForm.grade,/*年级id*/
						subject_id: this.$refs.testArea.ruleForm.subject,/*学科id*/
                        version_id: this.$refs.testArea.ruleForm.edition,/*版本id*/
                        masterial_id: this.$refs.testArea.ruleForm.material,/*教材id*/

						list_id: this.question.chapter.length > 0 ? this.question.chapter.pop() : 0,/*章节id*/
						know_id: this.question.knowled.length > 0 ? this.question.knowled.pop() : 0,/*知识点id*/
						blank_num: this.question.blankNum,/*填空题的空格数*/
						authority: 0,
					};
				}else{

					 params = {
						id: this.question.id,
						pattern: this.question.testType,/*1手动录入 2图片录入*/
						type_id: this.question.type,/*题型id*/

						content: this.question.imageUrl,/*题干*/
						resolve: this.question.resolveUrl,/*解析*/
						option: this.question.options,/*选项 以数组形式 如 option[0]['name'] option[0]['value']*/

						answer: this.question.check,/*答案 以数组形式 如 anseer[0] answer[1]*/
						difficulty_id: this.question.difficulty,/*难度id*/
                        keynote: this.question.keynote,/*重点程度 1低 2中 3高*/
                        
						grade_id: this.$refs.testArea.ruleForm.grade,/*年级id*/
						subject_id: this.$refs.testArea.ruleForm.subject,/*学科id*/
                        version_id: this.$refs.testArea.ruleForm.edition,/*版本id*/
                        masterial_id: this.$refs.testArea.ruleForm.material,/*教材id*/
                        
						list_id: this.question.chapter.length > 0 ? this.question.chapter.pop() : 0,/*章节id*/
						know_id: this.question.knowled.length > 0 ? this.question.knowled.pop() : 0,/*知识点id*/
						blank_num: this.question.blankNum,/*填空题的空格数*/
						authority: 0,
					};
				}
				
				this.$ajax.put('api/newtest/question', params, {func: {success: success}})
			
				// bus.$emit('setTest', this.question);

				/*if (this.$route.query.points) {
					this.$ajax.put('api/newtest/question', params, {func: {success: success}})
					this.$store.commit('SET_QUESTIONCHANGE', new Date())
					bus.$emit('setTest', this.question);
				}else{
					this.$ajax.put('api/newtest/question', params, {func: {success: success}})
				}*/
				
			},
			/**
			 * 从父级获取试题的对象参数
			 * @DateTime 2019-08-14T10:47:12+0800
			 */
			ObtainTest(){
				
				let self = this
				let obj = ''
				 obj = deep_clone(this.testObj)

				 this.question.testType = obj.pattern+''
				// this.timingDevice = setTimeout(function () {
					this.question.id = obj.id;
					this.question.baseid = obj.type_base_id;
					this.question.type = obj.qt_id;

					if (obj.pattern == 1) {/*手动*/

						this.question.stem = this.showImg(obj.content);
						this.question.resolve = this.showImg(obj.resolve);

					}else{/*图片*/
						let baseUrl = sessionStorage.getItem('host_addr');
						if (this.$route.query.points) {
							this.uploadOptions.imageUrl =  obj.content_path
							this.uploadOptions.resolveUrl =  obj.resolve_path
						}else{
							this.uploadOptions.imageUrl =  obj.content_image_path
							this.uploadOptions.resolveUrl =  obj.resolve_image_path
						}
						
					}
					this.question.answer  = []
					if (this.question.baseid  == 1 || this.question.baseid  == 2) {

						if(this.question.baseid  == 1 || this.question.baseid  == 4){

							this.question.check = obj.answer
						}else if(this.question.baseid  == 2){
							this.question.check = obj.answer
						}

						for (let i = 0; i < obj.option.length; i++) {

							this.question.answer.push(obj.option[i].name)
						}

					}else{
						this.question.check = obj.answer;
					}


					this.question.options = []
					this.question.options = obj.option != null ? obj.option : [];

					/*判断单选&多选题的选项长度不为0时， 重新改变图片的src*/
					if (this.question.options.length !== 0 && (obj.qt_id == 1 || obj.qt_id == 2)) {
						this.question.options.forEach((item, index)=>{
							item.value = this.showImg(item.value)
						})
					}
					this.question.blankNum = obj.blank_num
					this.question.difficulty = obj.difficulty_id;
                    this.question.keynote = obj.keynote;

					this.$refs.testArea.ruleForm.grade = obj.grade_id ? obj.grade_id : '';
					this.$refs.testArea.ruleForm.subject = obj.subject_id ? obj.subject_id : '';
					this.$refs.testArea.ruleForm.edition = obj.version_id ? obj.version_id : '';
                    this.$refs.testArea.ruleForm.material = obj.masterial_id ? obj.masterial_id : '';
                    
					this.question.chapter = obj.list_id_arr;	/*章节*/
					this.question.knowled = obj.know_id_arr;/*知识点*/

					let manual = new Promise((resolve, reject) => {
					    //做一些异步操作
					    setTimeout(() => {
					        resolve(this.$refs.testArea.ruleForm.material);
					    },1000);
					});
					manual.then((result) => {
						this.setMaterial(result)
					}) 
				
			},
			/**
			 * 富文本的img src重新赋值 避免破图
			 * @DateTime 2019-08-16T10:32:23+0800
			 * @param    {[type]}                 content [description]
			 * @return   {[type]}                         [description]
			 */
			showImg(content) {
				//截取分割img的src
				let temp = content.split('<img src="');
				let data = null;
				let baseUrl = sessionStorage.getItem('host_addr');
				temp.forEach((item, index) => {
					if (index === 0) {
						data = item;
					} else {
						data += '<img src="' + item;
					}
				})

				return data;
			},

			/**
			 * 请求题型数据
			 * @DateTime 2019-07-25T14:04:59+0800
			 * @return   {[type]}                 [description]
			 */
			getQuestionType(){

				let success = (res=>{
					this.questionTypeList = res.data;
					if (this.questionTypeList.length > 0) {
						this.questionTypeList.unshift({id: 0, name: '全部'})
					}
					this.loading = false
				});

				let params = {status: 1};

				this.$ajax({
					url: 'api/newtest/get_question_type',
					method: 'get',
					params: params,
					func: { success: success}
				})
			},

			/**
			 * [removeAnswer description]
			 * @DateTime 2019-09-02T16:55:19+0800
			 * @param    {[type]}                 obj  [description]
			 * @param    {[type]}                 type [description]
			 * @return   {[type]}                      [description]
			 */
			removeAnswer(type){

				var len = this.question.answer.length;
				let index = this.question.options.length;
				switch(type){
					case 1:
						if ( this.question.answer.length < 3) {return this.$message.error('不能再删除了....')}
						if ( this.question.baseid == 1 || this.question.baseid == 2)  {
							let a = this.question.answer.pop()
							for (let i = 0; i < this.question.check.length; i++) {
								let item = this.question.check[i]
								if ( a == item) {
									this.question.check.splice(i, 1)
								}
							}
						}
					break;
					case 2:
						if ( this.question.baseid == 1 &&  this.question.answer.length > 3) {
							return this.$message.error('不能再添加了....')
						}else if ( this.question.answer.length > 6) {
							return this.$message.error('不能再添加了....')
						}
						 this.question.answer.push(this.ChoiceArr[len])
					break;
					case 3:

						if ( this.question.options.length < 3) {return this.$message.error('不能再删除了....')}
						 this.question.options.pop();
						if ( this.question.baseid == 1 || this.question.baseid == 2)  {
							let a = this.question.answer.pop()
							for (let i = 0; i < this.question.check.length; i++) {
								let item = this.question.check[i]
								if ( a == item) {
									this.question.check.splice(i, 1)
								}
							}
						}
					break;
					case 4:
			
						if ( this.question.baseid == 1 &&  this.question.options.length > 3) {
							return this.$message.error('不能再添加了....')
						}else if ( this.question.options.length > 6) {
							return this.$message.error('不能再添加了....')
						}
						 this.question.options.push({
							name: this.ChoiceArr[index],
							value: ''
						})
						 this.question.answer.push(this.ChoiceArr[this.question.options.length-1])
					break;

				}

			},
			/**
			 * 获取章节选择的id
			 * @return {[type]} [description]
			 */
			chapterChange(val) {
			 
			  // this.question.chapter = val
			  // console.log(this.$refs.chapter.getCheckedNodes()[0].value);
			},
			/**
			 * 获取知识点选择的id
			 * @DateTime 2019-09-04T11:42:45+0800
			 * @param    {[type]}                 val [description]
			 * @return   {[type]}                     [description]
			 */
			knowledgeChange(val){
				// console.log(val ,9)
				// this.question.knowled = val
			},
			/**
			 * 请求章节数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getChapter(){
				if (this.$refs.testArea.ruleForm.material === '') {return};

				let success = (res=>{
					this.chapterList  = []

					res.data.forEach((item, index)=>{
						this.chapterList.push({
							value: item.id,
							label: item.name,
							children: []
						})

						if (item.children.length != 0) {
							item.children.forEach(child=>{
								this.chapterList[index].children.push({
									value: child.id,
									label: child.name
								})
							})
						}else{
							this.$set(this.chapterList[index], 'disabled', true)
							
						}
					})
				});

				let params = {}

				 params = {
					material_id: this.$refs.testArea.ruleForm.material,
					type: 1
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},
			/**
			 * 请求章知识点数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getKnowledge(){
				if (this.$refs.testArea.ruleForm.material === '') {return};

				let success = (res=>{
					this.knowledgeList  = []

					res.data.forEach((item, index)=>{
						this.knowledgeList.push({
							value: item.id,
							label: item.name,
							children: []
						})

						if (item.children.length != 0) {

							item.children.forEach(child=>{
								this.knowledgeList[index].children.push({
									value: child.id,
									label: child.name
								})
							})
						}else{
							this.$set(this.knowledgeList[index], 'disabled', true)
						}


					})
				});

				let params = {}

				 params = {
					material_id: this.$refs.testArea.ruleForm.material,
					type: 2
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},

			/**
			 * 判断教材是否为空，在不为空时，根据id筛选相关的试题
			 * @DateTime 2019-07-24T09:27:20+0800
			 * @param    {[Strong]}   val 教材id
			 */
			setMaterial(val){

				if (val != '') {
					this.getChapter()
					this.getKnowledge()
				}else{

					this.$refs.testArea.ruleForm.material = '';
					this.question.chapter =  '';	/*章节*/
					this.question.knowled =  '';	/*知识点*/
					this.chapterID = [];
					this.knowledgeID = [];
					this.chapterList = [];
					this.knowledgeList = [];
				}

			},

		}
	}
</script>